package cn.tedu.charging.order.mqtt;

import cn.tedu.charging.order.config.MqttConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * MQTT生产者
 * 消息发送者
 * 订单服务 给 EMQX 发送消息
 *
 * @Configuration    @Component 区别
 * 都是让spring 容器管理 Configuration 一个是配置相关的组件  Component 一个是和具体业务无关组件
 */

@Component
@Slf4j
public class MqttProducer {
    @Autowired
    private MqttClient mqttClient;
    /**
     * 通过 MqttClient 发送消息到 EMQX
     * @param topic
     * @param message
     * @return
     */
    public Boolean send(String topic,String message) {
        Boolean sussess = false;
        //topic是啥   消息分组
        //消息 需要把消息转换为字节数组  .getBytes() 字符串的方法 获取字节数组
        //质量是啥？ MQTT的QoS   https://blog.csdn.net/qq_35701988/article/details/140475338
        //保留是啥  retained    https://docs.emqx.com/zh/enterprise/v5.1/messaging/mqtt-retained-message.html

        try {
            mqttClient.publish(topic,message.getBytes(),0,false);
            sussess =true;
        } catch (MqttException e) {
            log.debug("给EMQX发送消息失败,topicL:{},消息:{}",topic,message,e);
        }
        return sussess;

    }
}
